package com.danskin.wechat.web;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.danskin.wechat.entity.AccountLog;
import com.danskin.wechat.entity.UserInfo;
import com.danskin.wechat.entity.WxMediaPlatform;
import com.danskin.wechat.model.LoginUser;
import com.danskin.wechat.service.AccountLogService;
import com.danskin.wechat.service.UserService;
import com.danskin.wechat.service.WxMediaPlatformService;
import com.danskin.wechat.util.JsonUtils;
import com.danskin.wechat.util.Page;

@Controller
@RequestMapping("manager")
public class ManagerController extends BaseController{
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private WxMediaPlatformService platformService;
	
	@Autowired
	private AccountLogService accountLogService;
	
	private  List<UserInfo> userInfoList=null;
	
	//========================================修改普通管理员密码============================//
	
	@RequestMapping("/toPassword")
	public String toPassword(HttpServletRequest request,Model model){
		//UserInfo user=(UserInfo) request.getSession().getAttribute("user");
		model.addAttribute("user", this.getLoginUser());
		return "manager/password_edit";
	}
	/**
	 * 修改 普通管理员（微信运营者） 密码
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/editPassword", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Object editUserBySelf() throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        Map requestParameter = getRequestParameter(this.getRequest());
        UserInfo user = userService.getUserByID(Integer.parseInt(String.valueOf(requestParameter.get("USER_ID"))));
        
        String Md5Password=DigestUtils.md5DigestAsHex(String.valueOf(requestParameter.get("OPASSWORD")).getBytes());
        if(user.getUserPwd().equals(Md5Password)){
        	if(((String)requestParameter.get("chkpwd")).equals((String)requestParameter.get("PASSWORD"))){
        		try {
        			Map<String,Object> paramter=new HashMap<String,Object>();
        			paramter.put("id", Integer.parseInt(String.valueOf(requestParameter.get("USER_ID"))));
        			paramter.put("userPwd", DigestUtils.md5DigestAsHex(String.valueOf(requestParameter.get("chkpwd")).getBytes()));
        			int i = userService.updatePasswordByPrimaryKeySelective(paramter);
        			if(i>0){
        				map.put("result", "success");
        			}else{
        				map.put("result", "error");
    	            	map.put("msg", "修改密码失败 稍后重试");
        			}
				} catch (Exception e) {
					map.put("result", "error");
	            	map.put("msg", "修改密码失败 稍后重试");
				}
        		
        	}else{
        		map.put("result", "error");
            	map.put("msg", "两次输入密码不正确");
        	}
        }else{
        	map.put("result", "error");
        	map.put("msg", "原始密码不正确");
        }
        
        return JsonUtils.objectToJson(map);
    }
	
	//===========================================账户 增删改查========================================//
	
	/**
	 * 添加账户跳转到页面  
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/addAccount", produces = "application/json;charset=UTF-8")
	public ModelAndView addAccount() throws Exception {
		ModelAndView mv =new ModelAndView();
		List<WxMediaPlatform> list = platformService.getListWxMediaPlatform(new HashMap<String, Object>());
		
		mv.addObject("list", list);
		mv.setViewName("manager/account_add");
		return mv; 
	}
	/**
	 * 向数据库  增加账号
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/toAddAccount", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String toAddAccount(@RequestBody Map requestParameter) throws Exception {
		//Map requestParameter = getRequestParameter(this.getRequest());
		Map<String,Object> map=new HashMap<String, Object>();
		UserInfo user=new UserInfo();
		if(requestParameter.containsKey("USERNAME")){
			user.setUserName((String)requestParameter.get("USERNAME"));
		}
		if(requestParameter.containsKey("PASSWORD")){
			user.setUserPwd((String)requestParameter.get("PASSWORD"));
		}
		if(requestParameter.containsKey("PHONE")){
			user.setMobile((String)requestParameter.get("PHONE"));
		}
		if(requestParameter.containsKey("EMAIL")){
			user.setEmail((String)requestParameter.get("EMAIL"));
		}
		if(requestParameter.containsKey("ROLE_ID")){
			user.setMpId(Integer.parseInt((String)requestParameter.get("ROLE_ID")));
		}
		user.setCreatedTime(new Date());
		user.setLastLoginTime(new Date());
		LoginUser session = this.getLoginUser();
		user.setRoleCode(1);
		user.setRoleName(session.getUserName());
		int i=userService.insertSelective(user);
			if(i>0){
				map.put("status", 200);
				map.put("msg", "保存成功");
			}else{
				map.put("status", 400);
				map.put("msg", "保存性息失败");
			}
			return 	JsonUtils.objectToJson(map);
		
	}
	
	/**
	 * 跳转到用户列表界面
	 * @return
	 */
	@RequestMapping(value = "/listAccount", produces = "application/json;charset=UTF-8")
	public ModelAndView listAccount(){
		ModelAndView mv=new ModelAndView();
		List<WxMediaPlatform> list = platformService.getListWxMediaPlatform(new HashMap<String, Object>());
		mv.addObject("list", list);
		mv.setViewName("manager/account_list");
		return mv;
	}
	/**
	 * 展示用户列表
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/showAccountList", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Object showAccountList(Page page) throws Exception{
		Map map = getRequestParameter(this.getRequest());
		map.put("roleId", 3);
		page.setMap(map);
		userInfoList = userService.getUserListByCondtion(page);
		
		return pagelistToJSONForBootStrapTable(userInfoList,page);
	}
	/**
	 * 跳转到更新账户  填充数据
	 * @param user
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/updateAccount", produces = "application/json;charset=UTF-8")
	public String updateAccount(Integer id,Model model) throws Exception{
		if(userInfoList!=null){
			for (UserInfo userInfo2 : userInfoList) {
				if(userInfo2.getId()==id){
					model.addAttribute("user",userInfo2);
					break;
				}
			}
		}
		List<WxMediaPlatform> list = platformService.getListWxMediaPlatform(new HashMap<String, Object>());
		model.addAttribute("list", list);
		
		return "manager/account_update";
	}
	/**
	 * 更新账户
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/toUpdateAccount", produces = "application/json;charset=UTF-8")
	public String toUpdateAccount() throws Exception{
		Map map = getRequestParameter(this.getRequest());
		map.put("createUser", this.getLoginUser().getUserName());
		map.put("createdTime", new Date());
		int i=userService.updateUserByPrimaryKeySelective(map);
		if( i>0){
			return "redirect:./listAccount";
		}else{
			return "redirect:./updateAccount";
		}
		
	}
	/**
	 * 删除账户
	 * @return
	 */
	@RequestMapping(value = "/deleteAccount", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String deleteAccount(Integer id){
		Map<String, String> map = new HashMap<String, String>();
		int i = userService.deleteUserById(id);
		if(i>0){
			map.put("status", "succese");
			map.put("msg", "删除成功");
		}else{
			map.put("status", "fail");
			map.put("msg", "删除失败");
		}
		return JsonUtils.objectToJson(map);
	}
	
	//================================账户日志==============================//
	/**
	 * 跳转到日志页面
	 * @return
	 */
	@RequestMapping(value = "/listAccountLog", produces = "application/json;charset=UTF-8")
	public ModelAndView listAccountLog(){
		ModelAndView mv=new ModelAndView();
		List<WxMediaPlatform> list = platformService.getListWxMediaPlatform(new HashMap<String, Object>());
		mv.addObject("list", list);
		mv.setViewName("manager/account_log");
		return mv;
	}
	/**
	 * 日志数据表格
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/showAccountLogList", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Object showAccountLogList(Page page) throws Exception{
		Map map = getRequestParameter(this.getRequest());
		page.setMap(map);
		List<AccountLog> list = accountLogService.listPageGetAccountLog(page);
		return pagelistToJSONForBootStrapTable(list,page);
	} 
	
//----------------------------------------数据备份-------------------------------------------------------------//
	/**
	 * 跳转到数据备份 
	 * @return
	 */
	@RequestMapping("toDataBackup")
	public String toDataBackup(){
		
		return "manager/data_backup";
	}
	/**
	 * 处理数据删除
	 * @param beginTime
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/dealDataBackUp", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String dealDataBackUp(@RequestBody JSONObject beginTime) throws Exception{
		Map<String, String> map = new HashMap<String, String>();
		Map<String, Object> param = new HashMap<String, Object>();
		int i=0;
		if(beginTime.containsKey("beginTime")){
			Date begin=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(beginTime.getString("beginTime"));
			param.put("beginTime", begin);
			param.put("mpId", this.getMpId());
			i = accountLogService.MoveScrmToLogForBackUp(param);
		}
		
		if(i>0){
			map.put("status", "succese");
			map.put("msg", "备份成功");
		}else{
			map.put("status", "fail");
			map.put("msg", "无可备份数据");
		}
		return JsonUtils.objectToJson(map);
	}
	
	
}
